<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use common\models\Sltopic;
use common\models\Shicai;
use yii\data\Pagination;
use common\components\FrontendHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SltopicController implements the CRUD actions for Sltopic model.
 */
class SltopicController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            // index页面缓存，永久有效
            'indexCache' => [
                'class' => 'yii\filters\PageCache',
                'only' => ['index'],
                'duration' => 0,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `id` FROM `sltopic` ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // view页面缓存，1天有效
            'viewCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['view'],
                'duration' => 86400,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `id` FROM `shicai` where `id`="'.\Yii::$app->request->get('id').'" ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // Http缓存
            'HttpCache' => [
                'class' => 'yii\filters\HttpCache',
                'only' => ['view'],
                'etagSeed' => function ($action, $params) {
                    $post = Shicai::find()->select(['id'])->where(['type_id'=>\Yii::$app->request->get('id')])->orderBy('id desc')->limit(1)->asArray()->one();
                    return serialize([$post]);
                },
            ],
        ];
    }

    /**
     * Lists all Sltopic models.
     * @return mixed
     */
    public function actionIndex() {
        $cache = Yii::$app->cache;
        $model = $cache->get("topicShicai");
        if ($model === false) {
            $types = array('乾果', '新鮮水果', '根莖類蔬菜', '水產類', '瓜果類蔬菜', '畜肉類', '禽蛋類', '米麵豆乳類', '莖葉類蔬菜', '菌菇類蔬菜', '魚類', '其他');
            foreach($types as $key => $value){
                $model[$key]['type'] = $value;
                $model[$key]['items'] = FrontendHelper::Shicai_type($value);
            }
            $cache->set("topicShicai", $model);
        }        
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Displays a single Sltopic model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $topic = Sltopic::find()->select('title')->where(['id' => $id])->asArray()->one();

        $query = Shicai::find()->where(['type_id' => $id])->andWhere(['enable' => 1])->asArray();
        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $query->count(),
        ]);
        $model = $query->orderBy('id desc')
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();
        $relate_type = \common\components\FrontendHelper::Sltopic_relate($id, 15);
        return $this->render('view', [
                    'title' => $topic['title'],
                    'type_id' => $id,
                    'model' => $model,
                    'pagination' => $pagination,
                    'relate_type' => $relate_type,
        ]);
    }

    /**
     * Finds the Sltopic model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Sltopic the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Sltopic::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
